#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import os
import random

from .FileHostProtoType import HostItem, FileHostProcess
from ..utility.gadget import cutstr



class mfitem(HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class mediafire(FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProcess.__init__(self)
        self.hostname = "MediaFire" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.isanoy = False
        self.logtype = 'poster'
        
        if self._user == 'anonymous':
            self.islogin = True
            self.isanoy = True
            self.fherr.write('Use [anonymous] to upload files to MediaFire...')
        
    def login(self):
        '''
        login to MediaFire
        return opener object which includes cookies
        '''
        self.generateOpener()
        
        if self.isanoy:
            return True     
        
        if self.check_cookie():
            return True
        
        self.fherr.write('login to MediaFire %s/%s...' % (self._user,'*'*len(self._pwd)))
        
        #login to mediafire requires no-empty cookie, so we should access his indexpage at first
        self.post_request("http://www.mediafire.com/")        
        
        #post login request
        loginData = {'returnto' : '/', 
                'login_email' : self._user, 
                'login_pass' : self._pwd,
                'submit_login.x' : str(random.randint(1,89)),
                'submit_login.y' : str(random.randint(1,89))}
        loginresult =  self.loginFileHost("http://www.mediafire.com/dynamic/login.php", loginData)
        #you always see you username at the top of the page, if it logins successfully.
        if 'et= 15' not in loginresult:
            self.fherr.write(loginresult)
            self.fherr.write("User %s Failed to Login MediaFire." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True

    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request("http://www.mediafire.com/")
        user = self._user.split('@')
        if response and user[0] in response and user[1] in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        #self.fherr.write(response)
        return False  
        
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        if self.isanoy:
            return self.upload_web_local_anonymous(file, progressLog, other_args, send_range)
        else:
            return self.upload_web_local_register(file, progressLog, other_args, send_range)
    
    def get_upload_info(self):
        randint = random.randint(10001,99998)
        url = "http://www.mediafire.com/basicapi/uploaderconfiguration.php?%d" % randint
        moreinfo = self.post_request(url)
        MFULConfig = cutstr(moreinfo, '<MFULConfig>', '</MFULConfig>')
        ukey = cutstr(moreinfo, '<ukey>', '</ukey>')
        user = cutstr(moreinfo, '<user>', '</user>')
        uploadkey = cutstr(moreinfo, '<folderkey>', '</folderkey>')
        return MFULConfig, ukey, user, uploadkey
        
    def comit_upload(self, uploadurl, file, MFULConfig, progressLog=None, send_range=None):
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        self.fherr.write(info) 
        basename = os.path.basename(file)   
        fileobj = open(file, 'rb')
        fileobj.seek(start_point)  
        data = {'Filedata' : fileobj}
        upload_response = self.post_request(uploadurl, data, cb=callback, \
                                            setfilename=filename,\
                                            setfilesize=filesize)
        uploadresponsekey = cutstr(upload_response, '<key>', '</key>')
        
        if not uploadresponsekey:
            #it seems something wrong >__<
            self.fherr.write("upload url: {}\n".format(uploadurl)) 
            self.fherr.write("upload response: {}\n".format(upload_response)) 
            self.fherr.write("Failed to get key after uploaded for %s" % file)
            return
            
        time.sleep(5)
        times = (self.wait_time - 20)/5
        wait_count = 0
        while times > 0:
            pollurl = "http://www.mediafire.com/basicapi/pollupload.php?key={}&MFULConfig={}"\
                            .format(uploadresponsekey, MFULConfig)
            upload_result = self.post_request(pollurl)
            if "No more" in upload_result:
                #success!
                quickkey = cutstr(upload_result, '<quickkey>', '</quickkey>')
                item = mfitem(basename, 'file', quickkey, "http://www.mediafire.com/?" + quickkey, filename)
                self.newupload.append(item)
                self.fherr.write("we wait %d times, and got the link!" % wait_count)
                self.fherr.write(item.format())
                return item
            time.sleep(15)
            times -= 1
            if "verif" in upload_result.lower():
                #we should wait the server verifying.
                wait_count += 1
                continue            
            else:
                #it seems something wrong >__<
                self.fherr.write("upload response: {}\nkey: {}\npollurl: {}\npollresult: {}"\
                                .format(upload_response, uploadresponsekey, pollurl, upload_result)) 
                self.fherr.write("Failed to get download link for %s" % file)
                return
        self.fherr.write("Time out, plz try to set a large wait-time. -_,-")
        
    def upload_web_local_register(self, file, progressLog=None, other_args=None, send_range=None):
        #get key from cookie
        ukey = ''
        user = ''
        for cookie in self._cj:
            if cookie.name == 'ukey':
                ukey = cookie.value
            elif cookie.name == 'user':
                user = cookie.value    
        if ukey == '' or user == '':
            self.fherr.write('Fail to get ukey&skey from cookies')
            return
        
        MFULConfig = self.get_upload_info()[0]
        uploadurl = "http://www.mediafire.com/douploadtoapi/?type=basic&ukey={}&user={}&uploadkey=myfiles&uploader=0&MFULConfig={}"\
                    .format(ukey, user, MFULConfig)
        return self.comit_upload(uploadurl, file, MFULConfig, progressLog, send_range)    
    
    def upload_web_local_anonymous(self, file, progressLog=None, other_args=None, send_range=None):
        MFULConfig, ukey, user, uploadkey = self.get_upload_info()
        uploadurl = "http://www.mediafire.com/douploadtoapi/?type=basic&ukey={}&user{}&uploadkey={}&filenum=0&uploader=0&MFULConfig={}"\
                    .format(ukey, user, uploadkey, MFULConfig)   
        return self.comit_upload(uploadurl, file, MFULConfig, progressLog, send_range)  
